package com.weijian.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Excel 相关工具类
 *
 * @author weijian
 */
@Slf4j
public class ExcelUtils {

    /**
     * 将 Excel 文件转换为 CSV 格式字符串
     *
     * @param multipartFile Excel 文件
     * @return CSV 格式字符串，如果转换失败或无数据则返回空字符串
     */
    public static String excelToCsv(MultipartFile multipartFile) {
        // 参数校验
        if (multipartFile == null || multipartFile.isEmpty()) {
            log.warn("上传文件为空");
            return "";
        }

        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("读取Excel文件时发生IO异常", e);
            return "";
        } catch (Exception e) {
            log.error("解析Excel文件时发生异常", e);
            return "";
        }

        if (CollUtil.isEmpty(list)) {
            log.info("Excel文件数据为空");
            return "";
        }

        // 转换为 CSV
        StringBuilder stringBuilder = new StringBuilder();
        
        // 读取表头
        LinkedHashMap<Integer, String> headerMap = (LinkedHashMap<Integer, String>) list.get(0);
        List<String> headerList = headerMap.values().stream()
                .filter(ObjectUtils::isNotEmpty)
                .collect(Collectors.toList());
        stringBuilder.append(StringUtils.join(headerList, ",")).append("\n");

        // 读取数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> dataMap = (LinkedHashMap<Integer, String>) list.get(i);
            List<String> dataList = dataMap.values().stream()
                    .filter(ObjectUtils::isNotEmpty)
                    .collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(dataList, ",")).append("\n");
        }
        
        return stringBuilder.toString();
    }
}
